package com.shortlink.common.user;

import cn.hutool.core.util.ObjectUtil;
import com.shortlink.common.constant.HeaderConstant;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户信息传输过滤器
 *
 * @author wp
 */
@Slf4j
public class UserTransmitFilter implements Filter {

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String userId = httpServletRequest.getHeader(HeaderConstant.USER_ID);
        String username = httpServletRequest.getHeader(HeaderConstant.USERNAME);
        UserInfoDTO userInfoDTO = null;
        if (ObjectUtil.isAllNotEmpty(userId, username)) {
            String groupName = httpServletRequest.getHeader(HeaderConstant.USER_GROUP_NAME);
            String groupLevel = httpServletRequest.getHeader(HeaderConstant.USER_GROUP_LEVEL);
            userInfoDTO = new UserInfoDTO(Long.valueOf(userId), username, groupName, Integer.valueOf(groupLevel));
            UserContext.setUser(userInfoDTO);
        }
        log.info(String.format("userInfo(%s) request(%s)", userInfoDTO, httpServletRequest.getServletPath()));
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}